package com.mos.service.impl;

import com.mos.base.Globl;
import com.mos.dao.AccessoryDao;
import com.mos.entity.Accessory;
import com.mos.service.AccessoryService;
import com.mos.support.enumeration.AccessoryType;
import com.mos.util.DateUtils;
import com.mos.util.FileUtil;
import com.mos.util.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Package Name: com.mos.service.impl
 * User: grq
 * Date: 2016/4/6
 * Time: 10:15
 * Description:some des here!
 */
@Service
@Transactional(readOnly = true)
public class AccessoryServiceImpl implements AccessoryService {

    @Autowired
    private AccessoryDao accessoryDao;

    public Accessory getById(String id) {
        return accessoryDao.getById(id);
    }

    public String getPath(String id) {
        Accessory accessory = accessoryDao.getById(id);
        if (accessory == null)
            return null;
        else
            return accessory.getPath();
    }

    public String[] uploadify(MultipartFile[] files) throws Exception {
        if (null == files || files.length == 0) throw new Exception("file not found . ");
        String[] resultFileName = new String[files.length];
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            String originalFilename = file.getOriginalFilename();
            String tmpFile = createTmpFileName(originalFilename);
            try {
                file.transferTo(new File(tmpFile));
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("");
            }
            tmpFile = tmpFile.replaceFirst(Globl.FILE_ROOT_DIR, "");
            resultFileName[i] = tmpFile;
        }

        return resultFileName;
    }

    public Map<String, String> upload(String name, String filePath) throws Exception {
        Map<String, String> result = new HashMap<String, String>();
        result.put("originalName", name);

        String tmpFile = createTmpFileName(name);
        try {
            FileUtil.copyFileToFile(filePath, tmpFile);
            result.put("tmpPath", tmpFile);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("");
        }
        return result;
    }

    public String saveUploadFile(String tmpFileName, String originalFileName, String type) throws Exception {

        if (StringUtils.isBlank(tmpFileName) || StringUtils.isBlank(originalFileName)) return null;

        if (!AccessoryType.SYSTEM.getCode().equals(type))
            tmpFileName = Globl.FILE_ROOT_DIR + tmpFileName;

        if (StringUtils.isBlank(type))
            type = AccessoryType.CUSTOM_DEFINE.getCode();

        String uploadPath = createUploadFilePath(type);//上传目录
        String fullFileName = uploadPath + File.separator + FileUtil.getSmpleFileName(tmpFileName);//最终文件名

        File file = new File(tmpFileName);
        Long size = file.length();//文件大小

        boolean copy = true;
        //copy文件
        try {
            copy = FileUtil.copyFileToFile(tmpFileName, fullFileName);
        } catch (Exception e) {
            copy = false;
            e.printStackTrace();
            throw new Exception("");
        }
        if (!copy) return null;

        String dbFileName = fullFileName.replaceFirst(Globl.FILE_ROOT_DIR, "");

        //保存记录
        String id = RandomUtil.createUuid();
        Accessory accessory = new Accessory();
        accessory.setId(id);
        accessory.setType(type);
        accessory.setPath(dbFileName);//路径
        accessory.setOriginalName(originalFileName);
        accessory.setSize(size);
        accessory.setCreaterId(Globl.SYSTEM_ID);
        accessory.setCreateTime(new Date());
        accessoryDao.add(accessory);

        return id;
    }

    //TODO
    public String getHtml(String id) {
        return null;
    }

    //TODO
    public String ckeditor(MultipartFile file) {
        return null;
    }

    //TODO
    public String saveContentFile(String content, String businessType, String suffix, String oldId) {
        return null;
    }


    @Transactional(readOnly = false)
    private String createTmpFileName(String originalFilename) {

        String dirPath = Globl.FILE_TMP_DIR;
        File dirFile = new File(dirPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        String newFileName = RandomUtil.createRandom();

        String suffix = FileUtil.getFileSuffix(originalFilename);//获取文件后缀
        if (StringUtils.isNotBlank(suffix)) newFileName += Globl.FILE_DOT + suffix;

        return (dirPath + newFileName).replace("\\", "/");
    }

    @Transactional(readOnly = false)
    private String createUploadFilePath(String type) {
        if (StringUtils.isBlank(type))
            type = AccessoryType.CUSTOM_DEFINE.getCode();
        String dirPath = Globl.FILE_UPLOAD_DIR + type + File.separator + DateUtils.formatDate(new Date(), "yyyyMM");
        File dirFile = new File(dirPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        return dirPath;
    }
}
